package com.fy.module.repo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.common.dto.PageDto;
import com.fy.common.exception.ServiceException;
import com.fy.common.vo.ApiRest;
import com.fy.common.vo.PageResult;
import com.fy.module.repo.entity.Repo;
import com.fy.module.repo.mapper.RepoMapper;
import com.fy.module.repo.service.IRepoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 题库 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2023-03-19
 */
@Service
public class RepoServiceImpl extends ServiceImpl<RepoMapper, Repo> implements IRepoService {
    @Override
    @Transactional
    public PageResult<Repo> findPage(PageDto<Repo> pageDto) {

        // 参数校验
        if(pageDto == null)
            throw new ServiceException("参数异常:1");

        if(pageDto.getNow() <= 0)
            throw new ServiceException("参数异常:2");

//        if(pageDto.getWhere().getTitle() == null)
//            throw new ServiceException("参数异常:3");
        //......
        //校验完毕

        //设置分页
        IPage<Repo> page = new Page<>(pageDto.getNow(), pageDto.getSize());
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper<>();

        // -模糊查询(如果where里面没有条件则默认查询全部数据，有的话就按条件查询)
        if(pageDto.getWhere().getTitle() != null)
        queryWrapper.like("title", pageDto.getWhere().getTitle());

        IPage pageInfo = this.page(page, queryWrapper);
        PageResult pageResult = new PageResult<>();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());

        return pageResult;
    }

    @Override
    @Transactional
    public ApiRest saveRepo(Repo repo) {
        if(repo == null){
            throw new ServiceException("参数异常");
        }

        repo.setCreateTime(new Date());
        repo.setUpdateTime(new Date());
        boolean save = this.saveOrUpdate(repo);
        return ApiRest.success();
    }
}
